package sequence

import (
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type Mysql struct {
	conn sqlx.SqlConn
}

const sql_replace = `REPLACE INTO sequence (stub) VALUES ('a')`

// NewMysql 创建mysql连接
func NewMysql(dsn string) Sequence {
	return &Mysql{conn: sqlx.NewMysql(dsn)}
}

// Next 取下一个号
func (m *Mysql) Next() ( uint64,  error) {
	stmt, err := m.conn.Prepare(sql_replace)
	if err != nil {
		logx.Errorw("conn.Prepare failed", logx.LogField{Key: "err", Value: err})
	}
	defer stmt.Close()
	res, err := stmt.Exec()
	if err != nil {
		logx.Errorw("stmt.Exec failed", logx.LogField{Key: "err", Value: err})
	}
	lid, err := res.LastInsertId()
	if err != nil {
		logx.Errorw("res.LastInsertId failed", logx.LogField{Key: "err", Value: err})
	}
	return uint64(lid), err
}
